package zerous.craft;

import android.view.*;
import android.util.*;
import android.content.*;
import android.graphics.*;

import zerous.craft.entity.*;

public class GameRenderer extends SurfaceView implements SurfaceHolder.Callback, Runnable
{
	public static int scrW,scrH;
	private Paint p,p2;
	private Thread t;
	public static Canvas c;
	private SurfaceHolder holder;
	private boolean isRunning;
	public static Player player;
	GameButton B;
	
	public GameRenderer(Context context, AttributeSet attrs)
	{
		super(context,attrs);
		
		holder = this.getHolder();
		holder.addCallback(this);
		p = new Paint();
		p2 = new Paint();
		p.setColor(Color.rgb(0,158,255));
		p2.setColor(Color.BLACK);
		
		Assets.load(context);
		setFocusable(true);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder)
	{
		scrW = this.getWidth();
		scrH = this.getHeight();
		isRunning = true;
		player = new Player(this.getWidth()/2,this.getHeight()/2);
		t = new Thread(this);
		//B = new GameButton(Assets.Fplayer,scrW-32,0);
		t.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder p1, int p2, int p3, int p4)
	{
		// TODO: Implement this method
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder p1)
	{
		isRunning = false;
	}
	
	@Override
	public void run()
	{
		while(isRunning)
		{
			draw();
			try
			{
				Thread.sleep(20);
			}
			catch(Exception e)
			{
				
			}
		}
	}
	
	public void draw()
	{
		try{
			addGUI();
			c = holder.lockCanvas();
			c.drawRect(0,0,this.getWidth(),this.getHeight(),p);
			c.drawText("x:"+player.turnX,40,40,p2);
			c.drawText("y:"+player.turnY,40,80,p2);
			player.draw(c,p);
			for(int i = 0;i<=scrW/2;i+=32)
			{
				for(int j = scrH/2+64;j<=scrH*2;j+=32)
				{
					BlockData.Grass.draw(c,p,i,scrH/2+32);
					BlockData.Stone.draw(c,p,i,j);
					BlockData.Stone.draw(c,p,scrW/2+64,scrH/2+128);
				}
			}
			
		}
		catch(Exception e)
		{

		}
		finally
		{
			if(c != null)
				holder.unlockCanvasAndPost(c);
		}
	}
	
	public void addGUI()
	{
		Bitmap UILayer = Bitmap.createBitmap(scrW,scrH,Bitmap.Config.ARGB_4444);
		Canvas UI = new Canvas(UILayer); 
	}
}
